
** Loading data - generated in dofile: data05
use "$data\minwage_data5_estimation_2012_2015.dta", clear
keep if inrange(tline, -24, 24) // keeping the relevant timeframe

* Creating a dataset consiting of  ID
* Ready for merge with DST data on school results
bysort pnr: keep if _n==1 
keep pnr aar

* Merging school results on
merge 1:m pnr using "E:\Data\rawdata\703788\udfk2002_2015.dta", nogen keep(match master) 
* keeping results from 9th grade, from standard exams, and so-called "normal classes"
keep if kltrin == 9 & proeveart == 1 & klassetype == 4

** creating 9 annual dataset with school results results by exam year
** generating results deciles based on standized version of grades.
forval x = 2007/2015{	
	preserve
		keep if skoleaar == `x'
		collapse (mean) grundskolekarakter (count) antal= grundskolekarakter (min) skoleaar, by(pnr)
		egen std_gpa = std(grundskolekarakter)
		xtile ptile = std_gpa, nq(10)
	save "$data\minwage_data6_stdgpa`x'.dta", replace
	restore
}	

** collecting the annual results in one dataset
use "$data\minwage_data6_stdgpa2007", clear
forval j=2008/2015{
	append using "$data\minwage_data6_stdgpa`j'",
}

** final data-set on GPA: 1 observations per individual.
bysort pnr: keep if _n==_N // keeping last year of results for few indivduals who has more than 1 grad. yr.
save "$data\minwage_data6_stdgpa.dta", replace
	
** Creating data set on on-going education	
use "$data\minwage_data5_estimation_2012_2015.dta", clear
keep if inrange(tline, -24, 24) // keeping the relevant timeframe

** Finding the observation closeth to 18th birthday
replace tline = tline * (-1) if tline < 0 // postive tline for all
bysort pnr: egen minetime = min(tline)
keep if minetime == tline // one observation per individual.

keep pnr aar

foreach var in hffsp igfsp{
	ge `var' = .
}

** merging information on education
forval t = 2012/2015{
	
	merge 1:1 pnr using "E:\Data\rawdata\703788\uddany`t'", nogen keep(match master) keepus(hffsp igfsp)
	replace hffsp = hffsp`t' if aar == `t' // merging information on completed information (only if education year = observation year)
	replace igfsp = igfsp`t' if aar == `t' // merging information on ongoing information (only if education year = observation year)
	
	drop hffsp`t' igfsp`t' 
}
** Saving data on ongoing education
save "$data\minwage_data6_ongoing_edu.dta", replace
	
	
